var dataset = [];
for (var i = 0; i < 21; ++i) {
	dataset[i] = 10;
}
var padding_Rose = {
	top: 30,
	rigth: 10,
	bottom: 20,
	left: 40
}; //边框
//获取所有玫瑰图div的宽高
var div4 = document.getElementsByClassName("AllRose")[0];
var width_Rose = div4.offsetWidth - padding_Rose.left - padding_Rose.rigth;
var height_Rose = div4.offsetHeight - padding_Rose.top - padding_Rose.bottom;
//所有小玫瑰图的是svg
var svg_rose = d3.select(".AllRose").append("svg")
	.attr("class", "svg_rose")
	.attr("preserveAspectRatio", "xMidYMid meet")
	.attr("viewBox", "0 0 " + width_Rose + " " + height_Rose);

var div5 = document.getElementsByClassName("Rose_DIV")[0];

var width_Big = div5.offsetWidth - padding_Rose.left - padding_Rose.rigth;
var height_Big = (div5.offsetHeight / 2) - padding_Rose.top - padding_Rose.bottom;

//第一个大的svg玫瑰图
svg_one = d3.select('.Rose_ONE').append('svg')
	.attr('class', 'svg_one')
	.attr("preserveAspectRatio", "xMidYMid meet")
	.attr("viewBox", "0 0 " + width_Big + " " + height_Big);

//第二个大的玫瑰图
svg_two = d3.select('.Rose_TWO').append('svg')
	.attr('class', 'svg_two')
	.attr("preserveAspectRatio", "xMidYMid meet")
	.attr("viewBox", "0 0 " + width_Big + " " + height_Big);

var pie = d3.layout.pie();
var piedata = pie(dataset);

var drag = d3.behavior.drag()
	.on("drag", dragmove);

var item = {};

var Team_rose = getTeams();
var lastRow = 0;

var sum = 0;
piedata.forEach(function(d, i) {
	d._endAngle = d.endAngle;
	d.endAngle = d.startAngle;
	d.duration = 1000 * (d.data / d3.sum(dataset)); //动画时长2秒，计算每一个弧形所用动画时间
	d.delaytime = sum;
	sum += d.duration;
});

function DrawAllRose(season) {
	d3.select(".svg_rose").selectAll("g").remove();
	var index = 0;
	console.log(Team);
	for (var i = 0; i < Team.length; ++i) {
		
		if ((season == '00-01' || season == '01-02') && (Team[i] == '新奥尔良鹈鹕')) {
			continue;
		}
		 else if ((season == '02-03' || season == '03-04') && (Team[i] == '夏洛特黄蜂')) {
			continue;
		}
		 else {
			DrawRose(Team[i], season, index, svg_rose, false);
			index++;
		}
	}
}

function getInit(season) {
	var datas = [];
	var k = 0;
	var extents = {};
	d3.csv("data/NBAYearCount.csv", function(data) {
		item = d3.keys(data[0]).filter(function(d) {
			return d != "NO" && d != "Season" && d != "Team"
		});
		var seasonData = [];
		for (var i = 0; i < data.length; ++i) {
			if (data[i].Season == season) {
				seasonData[k++] = data[i];
			}
		}
		for (var i = 0; i < item.length; ++i) {
			extents[item[i]] = d3.extent(seasonData, function(d) {
				return +d[item[i]].split("%")[0];
			});
		}
	}); //csv
	return extents;
}

function DrawRose(team, season, index, svg, isOne) {
	var RoseRadius;
	if (isOne == false) {
		RoseRadius = Math.min(width_Rose / 14, height_Rose / 10);
	} else {
		RoseRadius = svg[0][0].height.animVal.value / 4;
	}
	d3.csv("data/NBAYearCount.csv", function(data) {
		var extents = getInit(season);
		var IteamNo = {};
		var row = parseInt(index / 6);
		if (lastRow != row) {
			lastRow = row;
		}
		index = index % 6;
		item = d3.keys(data[0]).filter(function(d) {
			return d != "NO" && d != "Season" && d != "Team"
		});
		var seasonData = [];
		var k = 0;
		var myextents = {};
		//将单个赛季所有球队的数据提取出来
		for (var i = 0; i < data.length; ++i) {
			if (data[i].Season == season) {
				seasonData[k++] = data[i];
			}
		}
		//求每一项数据项的最大最小值
		for (var i = 0; i < item.length; ++i) {
			myextents[item[i]] = d3.extent(seasonData, function(d) {
				return +d[item[i]].split("%")[0];
			});
		}

		var color = d3.scale.category20();
		var seasonTeam;
		var Teams = [];
		var k = 0;
		for (var i = 0; i < data.length; ++i) {
			if (data[i].Season == season) {
				Teams[k++] = data[i];
			}
			if (data[i].Team == team && data[i].Season == season) {
				seasonTeam = data[i];
			}
		}
		for (var i = 0; i < item.length; ++i) {
			IteamNo[item[i]] = new Array;
			for (var j = 0; j < Teams.length; ++j) {
				IteamNo[item[i]].push(Teams[j][item[i]]);
			}
		}

		for (var key in IteamNo) {
			IteamNo[key].sort(function(a, b) {
				return a - b;
			});
		}
		var seasondata = [];
		for (var i = 0; i < item.length; ++i) {
			var d = {};
			d[item[i]] = seasonTeam[item[i]];
			var scale = d3.scale.linear()
				.domain([myextents[item[i]][0], myextents[item[i]][1]])
				.range([0.2, 1]);
			var realarc = d3.svg.arc()
				.innerRadius(0)
				.outerRadius(scale(seasonTeam[item[i]].split("%")[0]) * RoseRadius);
			d.arc = realarc;
			d.angle = piedata[i];
			seasondata[i] = d;
		}

		//绘图
		var teams = [];
		teams[0] = 10;

		var g_TeamRose = svg.selectAll('.g')
			.data(pie(teams))
			.enter()
			.append('g')
			.attr('class', team);
		//.each(function(d){
		//	d.dx = 0;
		//	d.dy = 0;
		//})
		//.call(drag);	


		if (isOne == false) {
			var rose_border = g_TeamRose.append('g')
				.attr('class', team + '-border')
				.append('rect')
				.attr('x', padding_Rose.left + RoseRadius * 2 * index - 24)
				.attr('y', padding_Rose.top + RoseRadius * 2 * row + 6)
				.attr('height', RoseRadius * 2)
				.attr('width', RoseRadius * 2)
				.attr('fill', 'white')
				.attr("stroke-width", 1)
				.attr('stroke', 'black')
				.attr('opacity', .5)
				.attr('stroke-opacity', .2)
				.on('mouseover',function(d){
					var thisTeam;
					for(var i = 0;i<Team_rose.length;++i){
						if(Team_rose[i].Team == team);
						thisTeam = Team_rose[i];
						break;
					}
					d3.select(this).append("svg:title")
						.text(thisTeam.Team + '(' + thisTeam.abb +')');
				})
				.on('click', function(d) {
					Rose_ClickTeam(team, season);
				})
		}

		var rose = g_TeamRose.append("g")
			.attr("class", team + "-rose")
			.attr("transform", function() {
				if (isOne == false) {
					return "translate(" + (padding_Rose.left + RoseRadius * 2 * index) + "," +
						(padding_Rose.top + 30 + RoseRadius * 2 * row) + ")";
				} else {
					return "translate(" + (padding_Rose.left + 20) + "," +
						(padding_Rose.top + 40) + ")";
				}
			});

		var arcs = rose.selectAll("g")
			.data(seasondata)
			.enter()
			.append("g");

		arcs.append("path")
			.attr("fill", function(d, i) {
				return color(i);
			})
			.attr("d", function(d, i) {
				return d.arc(d.angle);
			})
			.transition()
			.duration(function(d, i) {
				return d.angle.duration;
			})
			.ease("linear")
			.delay(function(d, i) {
				return d.angle.delaytime;
			})
			.attrTween("d", tweenArc(function(d, i) {
				return {
					startAngle: d.angle.startAngle,
					endAngle: d.angle._endAngle
				};
			}));
		arcs.on("mouseover", function(d) {
				d3.select(this).select("path")
					.transition()
					.duration(500)
					.ease("linear")
					.attr("transform", function(d, i) {
						var midAngle = (d.angle.startAngle + d.angle.endAngle) / 2;
						return "translate(" + (4 * Math.sin(midAngle)) + "," + (-4 * Math.cos(midAngle)) + ")";
					});
				d3.select(this).append("svg:title")
					.text(function(d) {
						var key, keychina;
						//获取球队属性名
						for (var k in d) {
							key = k;
							break;
						}
						//换成中文名
						for (var i = 0; i < signsItems.English_name.length; ++i) {
							if (signsItems.English_name[i] == key) {
								keychina = signsItems.Chinese_name[i];
							}
						}
						//返回球队排名
						for (var i = 0; i < IteamNo[key].length; ++i) {
							if (d[key] == IteamNo[key][i]) {
								return keychina + " NO:" + (i + 1);
							}
						}
					});
			}) //on mouseover
			.on("mouseout", function(d) {
				d3.select(this).select("path")
					.transition()
					.duration(500)
					.ease("linear")
					.attr("transform", function(d, i) {
						var midAngle = (d.angle.startAngle + d.angle.endAngle) / 2;
						return "translate(" + (1 * Math.sin(midAngle)) + "," + (-1 * Math.cos(midAngle)) + ")";
					});
			}); //on mouseout
	}); //csv
}

function tweenArc(b) {
	return function(a, i) {
		var d = b.call(this, a, i),
			i = d3.interpolate(a, d);
		//d保存转换之后的信息
		//插值模式，从d.endAnle=d.startAngle到d.endAngle=d._endAngle转换
		return function(t) {
			return a.arc(i(t));
		};
	};
}

function Rose_ClickTeam(team, season) {
	svg_one.selectAll('g').remove();
	svg_two.selectAll('g').remove();
	svg_two.selectAll('image').remove();
	DrawRose(team, season, 0, svg_one, true);
	svg_two.append('image')
	    .attr('class',team)
		.attr("xlink:href", function() {
			for(var i = 0;i<Team_rose.length;++i){
				console.log(team);
				if(Team_rose[i].Team == team){
					console.log(Team_rose[i].abb);
					return "logo/" + Team_rose[i].abb + "_logo.svg";
				}
			}
		})
		.attr("width", 80 + "px")
		.attr("height", 80 + "px")
		.attr("x",padding_Rose.left - 30 )
		.attr("y", 0);
	
	var g_svg_two = svg_two.append('g')
		.attr('class','svg_two_sign');
	
	g_svg_two.append('text')
		.attr('x',10)
		.attr('y',90)
		.text(team)
		.attr('font-size',12);
}

function dragmove(d) {
	console.log(d);
	d.dx += d3.event.dx;
	d.dy += d3.event.dy;
	d3.select(this).attr('transform', 'translate (' + d.dx + ',' + d.dy + ')');
}
